import CreateModal from '@/pages/Admin/InterfaceInfo/components/CreateModal';
import UpdateModal from '@/pages/Admin/InterfaceInfo/components/UpdateModal';
import {
  addInterfaceInfoUsingPOST,
  deleteInterfaceInfoUsingPOST,
  listInterfaceInfoByPageUsingGET,
  offlineInterfaceInfoUsingPOST,
  onlineInterfaceInfoUsingPOST,
  updateInterfaceInfoUsingPOST,
} from '@/services/api-backend/interfaceInfoController';
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {PageContainer, ProTable} from '@ant-design/pro-components';
import {Button, message} from 'antd';
import React, {useRef, useState} from 'react';

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.InterfaceInfo>({});

  /**
   * 新建接口
   *
   * @param fields
   */
  const handleAdd = async (fields: API.InterfaceInfo) => {
    const hide = message.loading('正在添加...');
    try {
      await addInterfaceInfoUsingPOST({...fields});
      message.success('创建成功！');
      handleModalOpen(false);
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      message.error('创建失败，' + error.message);
      return false;
    } finally {
      hide();
    }
  };

  /**
   * 修改接口
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.InterfaceInfo) => {
    const hide = message.loading('正在修改...');
    try {
      await updateInterfaceInfoUsingPOST(fields);
      message.success('修改成功！');
      handleUpdateModalOpen(false);
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      message.error('修改失败，' + error.message);
      return false;
    } finally {
      hide();
    }
  };

  /**
   * 删除接口
   *
   * @param record
   */
  const handleRemove = async (record: API.InterfaceInfo) => {
    const hide = message.loading('正在删除...');
    try {
      await deleteInterfaceInfoUsingPOST({
        id: record.id,
      });
      hide();
      message.success('删除成功！');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  /**
   * 发布接口
   *
   * @param record
   */
  const handleOnline = async (record: API.InterfaceInfo) => {
    const hide = message.loading('发布中...');
    try {
      await onlineInterfaceInfoUsingPOST({
        id: record.id,
      });
      hide();
      message.success('发布成功！');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('发布失败，' + error.message);
      return false;
    }
  };

  /**
   * 下线接口
   *
   * @param record
   */
  const handleOffline = async (record: API.InterfaceInfo) => {
    const hide = message.loading('下线中...');
    try {
      await offlineInterfaceInfoUsingPOST({
        id: record.id,
      });
      hide();
      message.success('下线成功！');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('下线失败，' + error.message);
      return false;
    }
  };

  const columns: ProColumns<API.InterfaceInfo>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'index',
      align: 'center',
    },
    {
      title: '接口名称',
      dataIndex: 'name',
      valueType: 'text',
      align: 'center',
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: '接口描述',
      dataIndex: 'description',
      valueType: 'textarea',
      align: 'center',
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '接口地址',
      dataIndex: 'url',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '接口参数',
      dataIndex: 'requestParams',
      valueType: 'textarea',
      align: 'center',
    },
    {
      title: '请求头',
      dataIndex: 'requestHeader',
      valueType: 'textarea',
      align: 'center',
    },
    {
      title: '响应头',
      dataIndex: 'responseHeader',
      valueType: 'textarea',
      align: 'center',
    },

    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      align: 'center',
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Default',
        },
        1: {
          text: '开启',
          status: 'Processing',
        },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      align: 'center',
      hideInForm: true,
      search: false,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      align: 'center',
      hideInForm: true,
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: 'center',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record);
          }}
        >
          修改
        </a>,
        record.status === 0 ? (
          <a
            key="online"
            onClick={async () => {
              await handleOnline(record);
            }}
          >
            发布
          </a>
        ) : (
          <a
            key="offline"
            onClick={async () => {
              await handleOffline(record);
            }}
          >
            下线
          </a>
        ),
        <a
          style={{color: 'red'}}
          key="delete"
          onClick={async () => {
            await handleRemove(record);
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            新建
          </Button>,
        ]}
        request={async (params: API.listInterfaceInfoByPageUsingGETParams) => {
          const res: any = await listInterfaceInfoByPageUsingGET({...params});
          return {
            data: res?.data.records || [],
            total: res?.data.total || 0,
          };
        }}
        columns={columns}
      />

      {/* 更新模态框 */}
      <UpdateModal
        values={currentRow}
        columns={columns}
        onCancel={() => {
          handleUpdateModalOpen(false);
        }}
        onSubmit={async (values) => {
          await handleUpdate(values);
        }}
        visible={updateModalOpen}
      />

      {/* 新建模态框 */}
      <CreateModal
        columns={columns}
        onCancel={() => {
          handleModalOpen(false);
        }}
        onSubmit={async (values) => {
          await handleAdd(values);
        }}
        visible={createModalOpen}
      />
    </PageContainer>
  );
};

export default TableList;
